from book import Book


class Crawler():
    """爬虫的基类，搜索图书信息并爬取网页数据"""

    def __init__(self, keyword: str) -> None:
        """类的构造函数

        Args:
            keyword (str): 要查询图书的名称
        """
        self.book_name = keyword

        # 查询图书的结果，Book对象的列表
        self.book_data = []

    def save_book(self, file_name: str) -> None:
        '''将查询结果/书名，写入指定的txt文件'''
        with open(file_name, mode="w", encoding="utf-8") as fn:
            # 计数
            row_count = 0
            print("===开始写文件===")

            for book in self.book_data:                
                # 每本图书信息作为一行数据写入
                # 格式形如：[1]Python编程基础
                row_count = row_count + 1
                # 1）由save_book方法来格式化
                # fn.writelines("[{0}]书名：{1}\t，作者：{2}\t，出版社：{3}".format(
                #     row_count, book.title, book.author, book.press))

                # 2）由Book来来格式化
                # row_count = self.book_data.index(book)+1
                fn.writelines('[{0}]\n{1}\n'.format(row_count, book))
            
            print("===完成写文件===")

    # 析构函数
    def __del__(self):
        # 销毁对象，释放资源
        del self.book_data


if __name__ == "__main__":
    # 创建一个类的对象
    spider = Crawler('Python')

    # 创建一个图书Book类的测试对象
    book = Book('Python编程基础', '曹文', '机械工业出版社')
    spider.book_data.append(book)

    # 调用成员方法
    spider.save_book('query_book/data/book_db.txt')
